<template>
  <div ref="split" class="split">
    <div ref="leftView" class="left-view">
      <div ref="testTree" class="test-tree-box">
        <TestTree ref="testTreeRef" v-model:current="currentCase" v-model:testStatus="testStatus"
          v-model:treeRootName="treeRootName" :taskId="taskInfo.id" />
      </div>
      <div ref="leftParams" class="left-params-box">
        <LeftParams ref="leftParamsRef" :testStatus="testStatus" />
      </div>
    </div>
    <div ref="rightView" class="right-view">
      <div class="right-ct">
        <div class="tit">{{ currentCase.name }}</div>
        <div class="r-ct">
          <div ref="chartTable" class="chart-table">
            <div ref="chartBox" v-show="![4, 16, 17].includes(caseType)">
              <ChartView ref="chartViewRef" class="chart-view" :dataLen="chartData.length" :caseName="currentCase.name">
              </ChartView>
              <el-select v-if="false" :disabled="testStatus === 2" class="angle-select" placeholder="角度" v-model="angle"
                @change="setChartTableData(false)">
                <el-option v-for="item in angleOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <div ref="tableBox">
              <div class="table-box">
                <div class="tab-ct" :style="`height: calc(100% - ${[16, 17].includes(caseType) ? 12 : 29}px)`"
                  v-loading="resultLoading">
                  <TableBox v-if="tab == 1" ref="tableViewRef" :caseName="currentCase.name" :tableList="chartData"
                    :treeRootName="treeRootName" :caseType="caseType" :testStatus="testStatus">
                  </TableBox>
                  <TestLog v-if="tab == 2" ref="testLog" />
                  <!-- <div v-show="tab == 3" class="tab-body">SOAP交互内容</div> -->
                </div>
                <div class="tab-list" v-if="![16, 17].includes(caseType)">
                  <div v-for="(item, index) in tabList" :key="index" class="item" :class="{ active: item.value == tab }"
                    @click="tab = item.value">
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div ref="paramsTurn" class="params-turn">
            <ParamsView ref="paramsBoxRef" class="params-view" :caseId="currentCase.id"></ParamsView>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">


import { useTestStore } from "../store/testStore";

const dataEvent = (data: any) => {
  console.log("子组件收到数据了", data);
  handleEvent(data);
}

defineExpose({
  dataEvent
})

// 2. 实例化组合式 store
const testStore = useTestStore();

// 验证存储结果
console.log("存储后 Pinia 中的值：", testStore.sendTestCmd);

import "@xc-components/xc-form/lib/style.css";
import "@xc-components/xc-table/lib/style.css";

import { ref, defineOptions, onMounted, onUnmounted, computed, getCurrentInstance, onBeforeUnmount, watch, nextTick } from "vue";
import TestTree from "./components/TestTree.vue";
import ChartView from "./components/ChartView.vue";
import TableBox from "./components/TableBox/index.vue";
import ParamsView from "./components/ParamsView.vue";
import TestLog from "./components/TestLog.vue";
import LeftParams from "./components/LeftParams.vue";
import Split from "split.js";
import { openTask, closeTask, getTestCaseReults, getTestCaseConfig } from "../api/test/index";
import type { TestResultItem } from "../api/test/index.d";
import type { CreateTaskParams, CaseType } from "../api/task/index.d";
import type { OptionItem } from "../api/index.d";
// import { useRoute } from "vue-router";
import useConfig from "./hooks/useConfig";
import { onActivated } from "vue";
import { ElMessage } from "element-plus";
import { useDialogFre } from "../common";
import "../common/style.css";
import { createApp } from 'vue'; // 宿主应用自己的 Vue
import ElementPlus from 'element-plus'; // 宿主应用自己的 ElementPlus

// import createDialog from "./hooks/useDialogFre";
// import createDialog from "./hooks/useDialog";

// 智能检测环境并导入对应弹窗
let createDialog: any;

// 真实检测模块联邦环境
const isFederationEnv = () => {
  // 检测是否存在模块联邦的共享作用域
  if (typeof window === 'undefined') return false;

  // 检测模块联邦的特定标志
  const hasSharedScope = (window as any).__federation_shared__ !== undefined;
  const hasModuleRegistry = (window as any).System !== undefined || (window as any).webpackShareScope !== undefined;
  const hasPlatformVue = (window as any).Vue?.createApp !== undefined;

  return hasSharedScope || hasModuleRegistry || hasPlatformVue;
};

// // 动态导入对应弹窗
// if (isFederationEnv()) {
//   // 模块联邦环境：使用平台集成弹窗
//   createDialog = (params: any) => {
//     // 这里使用原来的useDialog逻辑
//     return import('./hooks/useDialog').then(mod => mod.default(params));
//   };
// } else {
//   // lib模式：使用独立弹窗
//   createDialog = (params: any) => {
//     return import('./hooks/useDialogFre').then(mod => mod.default(params));
//   };
// }

import { dialogCallback } from "../api/test/index";

// 包装成同步调用
const showDialog = async (config: any, taskId: string) => {
  // const createFn = isFederationEnv() 
  //   ? (await import('./hooks/useDialog')).default
  //   : (await import('./hooks/useDialogFre')).default;
  // const createFn = (await import('./hooks/useDialogFre')).default;

  return useDialogFre({
    config,
    bizData: taskId,
    onCallback: async (params) => {
      await dialogCallback(params, { taskId });
    },
  },
    { Vue: { createApp }, ElementPlus }
  );
};

// 定义全局变量
let splitList: any[] = [];

const testTreeRef = ref<InstanceType<typeof TestTree>>(); // 测试例
const leftParamsRef = ref<InstanceType<typeof LeftParams>>(); // 左侧参数
const chartViewRef = ref<InstanceType<typeof ChartView>>(); // 折线图
const tableViewRef = ref<InstanceType<typeof TableBox>>(); // 表格
const paramsBoxRef = ref<InstanceType<typeof ParamsView>>(); // 参数
const testLog = ref<InstanceType<typeof TestLog>>(); // 日志

const taskInfo = ref<Partial<CreateTaskParams>>({ id: String(testStore.taskId || "") }); // 任务信息
const testStatus = ref(1); // 测试状态 1:初始状态 2：测试中 3：暂停中
const currentCase = ref<Partial<CaseType>>({}); // 当前选中的测试例

const chartData = ref<TestResultItem[]>([]); // 图表数据

const treeRootName = ref(""); // 根节点名称，用于确认使用哪个图表、表格配置项

watch(() => testStore.taskId, (val) => {
  taskInfo.value.id = val;
});
const angle = ref<number | string>(""); // 当前角度，初始为空字符串
const angleOptions = ref<OptionItem[]>([]); // 角度下拉选择的配置
const angleGroup = ref<{ [key: string]: TestResultItem[] }>({}); // 角度分组数据，key是角度，value是结果列表

const tab = ref(1);
const tabList = [
  { name: "结果", value: 1 },
  { name: "输出", value: 2 }
  // { name: "SOAP交互", value: 3 }
];
const resultLoading = ref(false);

// 测试例类型
const caseType = computed(() => {
  return useConfig().getJson(currentCase.value.name, [], treeRootName.value).type;
});

watch(
  () => currentCase.value.id,
  (val) => {
    // 不处于测试中
    if (val && testStatus.value !== 2) {
      getCaseReults();
      getCaseConfig();
    }
    // 识别信号能力，隐藏图表
    console.log(caseType.value);
    splitList[2]?.setSizes([4, 16, 17].includes(caseType.value) ? [0, 100] : [68, 32]);
  }
);
watch(testStatus, (_, oldVal) => {
  if (oldVal === 1) {
    // 开始测试清空数据
    clearTestData();
  }
});
onMounted(() => {
  handleOpenTask(); // 打开任务，并获取测试例以及环境参数
  initSplit(); // 分割视图
  window.addEventListener("beforeunload", closeFn); // 注册事件，刷新页面关闭任务
});
onBeforeUnmount(() => {
  window.removeEventListener("beforeunload", closeFn); // 移除事件
  closeFn(); // 关闭任务
});
onActivated(() => {
  nextTick(() => {
    chartViewRef.value?.chartResize();
  });
});
onUnmounted(() => {
  console.log("测试页面卸载，清除事件");
})
const closeFn = () => {
  closeTask(undefined, { taskId: taskInfo.value.id }); // 关闭任务
};

type EventData = { dataName?: string; data: any };
const handleEvent = (param: EventData) => {

  const { dataName, data } = param || {};

  console.log("dataName", dataName, "data", data);

  switch (dataName) {
    case "TestResult":
      {
        // 测试结果
        if (caseType.value === 6) {
          // 无线电监测测向-测向精度
          setDataGroup(data); // 现将数据加入到分组中
          // 角度改变，清空数据
          if (angle.value !== data.refAngle) {
            angle.value = data.refAngle;
            chartData.value = [];
          }
        }
        chartData.value.push(data); // 加入数据
        chartViewRef.value?.drawChart(chartData.value, treeRootName.value); // 绘制图表
        tableViewRef.value?.scrollBottom(); // 结果表格，滚动到底部
        // 接收到消息时，测试状态改为测试中
        if (testStatus.value === 1) {
          testStatus.value = 2;
        }
      }
      break;
    case "TestCaseChanged":
      {
        // 测试例改变
        if (data.id !== currentCase.value.id) {
          chartData.value = [];
          paramsBoxRef.value?.getConfigData(data.config); // 更新参数内容
        }
        currentCase.value = { ...data, config: [] }; // 修改测试例选中项
        nextTick(() => {
          testTreeRef.value?.setTreeNodeData(); // 更新当前测试例状态
        });
      }
      break;
    case "TestState":
      {
        console.log("测试状态", data);
        // 结束测试
        if (["MeasureStartop", "WaitForMeasure"].includes(data)) {
          testStatus.value = 1; // 还原测试状态
          testStore.updateState({ testStatus: 1 });
        } else if (data === "MeasurePause") {
          testStatus.value = 3; // 暂停测试
        }
      }
      break;
    case "TestLog":
      {
        console.log("测试日志：", data);
        testLog.value?.setTestLog(data);
      }
      break;
    case "TestStatus":
      {
        leftParamsRef.value?.setData(data); // 获取测试情况
      }
      break;
    case "TestDialogEvent":
      {
        // 对话框消息
        console.log("对话框消息：", data);
        if (data.tipDialogType === "DynamicFormDialog") {
          data.result = JSON.parse(JSON.stringify(data.params));
        }
        showDialog(data || {}, taskInfo.value.id || "");
      }
      break;
    case "TestMessageEvent":
      ElMessage({
        message: data.message,
        type: data.type || "info"
      });
  }
};

/**
 * @description: 分割视图
 * @return {*}
 */
const initSplit = () => {
  const { leftView, rightView, chartTable, paramsTurn, chartBox, tableBox, testTree, leftParams } = getCurrentInstance()?.refs || {};
  const options = [
    { el: [leftView, rightView], direction: "horizontal", sizes: [15, 85] },
    { el: [chartTable, paramsTurn], direction: "horizontal", sizes: [70, 30] },
    { el: [chartBox, tableBox], direction: "vertical", sizes: [68, 32], minSize: [0, 100] },
    { el: [testTree, leftParams], direction: "vertical", sizes: [60, 40] }
  ];
  splitList = [];
  options.forEach((x: any) => {
    const split = Split(x.el, {
      snapOffset: 0,
      gutterSize: 10,
      onDrag: () => {
        chartViewRef.value?.chartResize();
      },
      onDragEnd: () => {
        console.log("拖动结束");
      },
      ...x
    });
    splitList.push(split);
  });
};

/**
 * @description: 打开任务
 * @return {*}
 */
const handleOpenTask = async () => {
  console.log("打开任务");
  const taskId = String(testStore.taskId || "");
  const { data } = await openTask(undefined, { taskId });
  console.log("准备获取左侧树结构数据↓");
  testTreeRef.value?.getTreeData(); // 获取测试例
  console.log("准备获取左侧树结构数据↑");
  leftParamsRef.value?.getData(); // 获取环境参数
  if (data === "[]") return;
};

/**
 * @description: 获取当前测试例结果
 * @return {*}
 */
const getCaseReults = async () => {
  chartData.value = [];
  resultLoading.value = true;
  const { data } = await getTestCaseReults({ testCaseId: currentCase.value.id || "" }, { taskId: taskInfo.value.id });
  resultLoading.value = false;
  chartData.value = String(data) === "[]" ? [] : data || [];
  setChartTableData(true);
};

/**
 * @description: 绘制图表以及表格渲染
 * @return {*}
 */
const setChartTableData = (reset = true) => {
  nextTick(() => {
    // 无线电监测测向-测向精度
    if (caseType.value === 6) {
      chartData.value = reset ? handleGroup(chartData.value) : angleGroup.value[angle.value] || [];
    }
    chartViewRef.value?.drawChart(chartData.value, treeRootName.value);
    tableViewRef.value?.scrollBottom(true);
  });
};

/**
 * @description: 图表、表格数据根据角度分组
 * @param {*} data
 * @return {*}
 */
const handleGroup = (data: TestResultItem[]) => {
  angleGroup.value = {};
  angleOptions.value = [];
  data.forEach((item) => setDataGroup(item));
  angle.value = data[0]?.refAngle || 0;
  return angleGroup.value[angle.value] || [];
};
/**
 * @description: 将结果数据加入到对应的组中
 * @param {*} row
 * @return {*}
 */
const setDataGroup = (row: TestResultItem) => {
  const key = row.refAngle || 0;
  if (angleGroup.value[key]) {
    angleGroup.value[key].push(row);
  } else {
    angleGroup.value[key] = [row];
    angleOptions.value.push({ label: row.refAngle + "°", value: Number(row.refAngle || 0) });
  }
};

/**
 * @description: 获取当前测试例配置
 * @return {*}
 */
const getCaseConfig = async () => {
  paramsBoxRef.value?.getConfigData([]);
  const { data } = await getTestCaseConfig({ caseId: currentCase.value.id || "" }, { taskId: taskInfo.value.id });
  nextTick(() => {
    paramsBoxRef.value?.getConfigData(data || []);
  });
};

/**
 * @description: 清除数据
 * @return {*}
 */
const clearTestData = () => {
  chartData.value = [];
  testLog.value?.clearTestLog();
  if (caseType.value === 6) {
    angle.value = "";
    angleOptions.value = [];
    angleGroup.value = {};
  }
};

</script>

<style scoped lang="scss">
.split {
  display: flex;
  height: 100%;
  color: #333;
  overflow: hidden;
  font-size: 12px;
  background: #fff;

  .left-view {
    background-color: #f3f3f3;
    height: 100%;
    min-width: 180px;
    display: flex;
    flex-direction: column;

    .test-tree-box {
      flex: 1;
    }

    .left-params-box {
      background-color: #fff;
    }
  }

  .right-view {
    background: #fff;
    overflow: hidden;

    .right-ct {
      margin: 10px 10px 10px 0;
      border: 1px solid #eaeaea;
      height: calc(100% - 20px);
    }

    .tit {
      padding: 0 16px;
      font-weight: bold;
      height: 38px;
      line-height: 38px;
      background-color: #f4f4f4;
      border-bottom: 1px solid #eaeaea;
    }

    .r-ct {
      display: flex;
      height: calc(100% - 59px);
      margin: 10px;

      .chart-table {
        position: relative;
        border: 1px solid #eaeaea;

        .table-box {
          height: 100%;

          .tab-ct {
            height: calc(100% - 29px);

            .tab-body {
              height: calc(100% - 20px);
              padding: 10px;
            }
          }

          .tab-list {
            display: flex;
            background-color: #f4f4f4;
            box-sizing: border-box;
            position: relative;

            // &::before {
            //   content: "";
            //   position: absolute;
            //   border-top: 1px solid #eaeaea;
            //   width: 100%;
            // }
            .item {
              height: 28px;
              line-height: 28px;
              padding: 0 12px;
              border-right: 1px solid #eaeaea;
              position: relative;
              z-index: 1;
              border-top: 1px solid transparent;
              cursor: pointer;

              &:hover {
                background-color: #dddddd;
              }

              &.active {
                background-color: #fff;
              }
            }
          }
        }

        :deep(.angle-select) {
          position: absolute;
          top: 10px;
          right: 10px;
          width: 120px;

          .el-select__wrapper {
            --el-border-color: #ccc;
          }
        }
      }

      .params-turn {
        .params-view {
          // border: 1px solid #eaeaea;
          height: 100%;
          box-sizing: border-box;
        }

        .turn-view {
          border: 1px solid #eaeaea;
          height: 100%;
          box-sizing: border-box;
        }
      }
    }
  }
}

:deep(.gutter) {
  background-repeat: no-repeat;
  background-position: 50%;
  height: 100%;
  background-color: transparent;
  min-width: 10px;
}
</style>
